using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Shadow : MonoBehaviour
{
    private Transform playerTransform;      //player位置
    private SpriteRenderer shadowSprite;
    private SpriteRenderer playerSprite;

    private Color _color;

    [Header("不透明度控制")] 
    public float startAlpha;                //shadow初始的不透明度
    public float alphaMultiplier;           //alpha的渐变系数
    private float alpha;

    [Header("显示时间控制")] 
    public float activeTime;                //shadow的显示时间
    private float startActiveTime;          //shadow开始显示时的系统时间


    private void OnEnable()
    {
        playerTransform = GameObject.FindGameObjectWithTag("Player").transform;
        shadowSprite = gameObject.GetComponent<SpriteRenderer>();
        playerSprite = GameObject.FindGameObjectWithTag("Player").GetComponent<SpriteRenderer>();
        
        //将player的位置、sprite信息赋值给残影
        transform.position = playerTransform.position;
        transform.rotation = playerTransform.rotation;
        transform.localScale = playerTransform.localScale;
        shadowSprite.sprite = playerSprite.sprite;

        alpha = startAlpha;
        startActiveTime = Time.time;
    }

    // Update is called once per frame
    void Update()
    {
        ChangeAlpha();//让残影逐渐透明（通过spriteRender的alpha值来控制）
        DisappearShadow();//残影显示一段时间后，放回对象池
    }

    private void ChangeAlpha()
    {
        alpha *= alphaMultiplier;
        _color = new Color(0.8f, 0.8f, 1, alpha);
        shadowSprite.color = _color;
    }

    private void DisappearShadow()
    {
        if (Time.time > (startActiveTime + activeTime))
        {
            //放回对象池
            ShadowPool.instance.EnPool(this.gameObject);
        }
    }
}
